package ch.zbw.sysventory.agent.scanner.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

import ch.zbw.sysventory.transport.model.Printer;

public class PrinterScanner {

	Logger logger = Logger.getRootLogger();

	private String driverName;
	private String driverNameV;

	public List<Printer> getPrinters() {
		List<Printer> printers = new ArrayList<Printer>();

		try {
			ActiveXComponent axWMI = new ActiveXComponent(String.format("winmgmts:\\\\%s\\root\\CIMV2", "localhost"));
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant("SELECT * FROM Win32_Printer"));
			Variant vCollectionV = axWMI.invoke("ExecQuery", new Variant("SELECT * FROM Win32_PrinterDriver"));

			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();

				Printer printer = new Printer();

				printer.setName(Dispatch.call(item, "Name").toString().trim());
				driverName = Dispatch.call(item, "driverName").toString().trim();
				printer.setDriver(driverName);

				Dispatch itemV = null;
				EnumVariant enumVariantV = new EnumVariant(vCollectionV.toDispatch());
				while (enumVariantV.hasMoreElements()) {
					itemV = enumVariantV.nextElement().toDispatch();
					driverNameV = Dispatch.call(itemV, "name").toString().trim();

					if (driverNameV.contains(driverName)) {
						printer.setDriverVersion(Dispatch.call(itemV, "Version").toString().trim());
						break;
					}
				}

				printers.add(printer);
			}
		} catch (Exception e) {
			logger.error("Cannot read printers: " + e.getMessage(), e);
		}

		return printers;
	}
}
